﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using ReportGenerators._1Clinic;
using CustomSecurity;
using GeneralLibs;

namespace ReportGenerators._1Clinic
{
    public partial class FrmTongHopSuDungDichVu : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopSuDungDichVu()
        {
            InitializeComponent();
        }

        DsBaoCaoClinicChung dsTongHopSuDungDichVu = new DsBaoCaoClinicChung();

        private void FrmTongHopSuDungDichVu_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Hôm nay";

                #region cmbBacSy
                string maNhom = "BacSi";
                cmbBacSi.DataSource = UserList.Instance.GetDanhSachNguoiDungByMaNhom(maNhom).DefaultView;
                cmbBacSi.DisplayColumn = "FullName";
                cmbBacSi.ValueColumn = "ID";
                cmbBacSi.AddVisibleColumn("FullName", "Tên bác sĩ");
                #endregion

                #region cmbPhongBan
                cmbPhongBan.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucPhongBan().DataView;
                cmbPhongBan.DisplayColumn = "Ten";
                cmbPhongBan.ValueColumn = "ID";
                cmbPhongBan.AddVisibleColumn("Ma", "Mã", 100, 1);
                cmbPhongBan.AddVisibleColumn("Ten", "Tên", 320, 2);
                #endregion

                gridControl.DataSource = dsTongHopSuDungDichVu.BCTongHopDichVu;

                FormatGridViewForCopyCell(gridView); //KCB thì cho copy trong các report
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }

            FormatNumberInGridView(gridView);
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void cmbBacSi_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbBacSi.EditValue = Guid.Empty;
        }
        private void cmbPhongBan_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbPhongBan.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBarDev.StartShowProgress();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                //Các điều kiện tìm kiếm
                string bacSiCondition = "1 = 1";
                string phongBanCondition = "1 = 1";
                string BHYTCondition = "1 = 1";

                if (cmbBacSi.EditValue != null && (Guid)cmbBacSi.EditValue != Guid.Empty)
                    bacSiCondition = string.Format("'{0}'", cmbBacSi.EditValue);
                if (cmbPhongBan.EditValue != null && (Guid)cmbPhongBan.EditValue != Guid.Empty)
                    phongBanCondition = string.Format("'{0}'", cmbPhongBan.EditValue);

                if (chkCoBHYT.Checked && !chkKhongBHYT.Checked) //lấy có thẻ BHYT
                    BHYTCondition = string.Format("SoTheBHYT <> ''");
                else if (!chkCoBHYT.Checked && chkKhongBHYT.Checked) //lấy không có thẻ BHYT
                    BHYTCondition = string.Format("(SoTheBHYT = '' OR SoTheBHYT IS NULL)");
                else if (!chkCoBHYT.Checked && !chkKhongBHYT.Checked) //k tích cả 2 --> không lấy gì
                    BHYTCondition = "1 = 0";

                //Buil sql Query
                dsTongHopSuDungDichVu.BCTongHopDichVu.Clear();
                int count = 0;

                cmd.CommandText = string.Format("SELECT C.Ma MaDV, C.Ten TenDV, C.DonViTinh, COUNT(B.DichVuID) SoLuong,  \n" +
                                                "   AVG(B.GiaBan) GiaBanTB, SUM(GiaBan) - SUM(B.ThanhTien) ChietKhau, SUM(B.ThanhTien) ThanhTien \n" +
                                                "FROM Clinic_Phieu A INNER JOIN Clinic_KhoanMucPhieu B ON A.ID = B.PhieuID \n" +
                                                "	INNER JOIN Clinic_DichVu C ON B.DichVuID = C.ID \n" +
                                                "WHERE {0} AND {1} AND {2} \n" +
                                                "	AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                                "GROUP BY C.Ma, C.Ten, C.DonViTinh, B.GiaBan \n",
                                                bacSiCondition, phongBanCondition, BHYTCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                if (dsTongHopSuDungDichVu != null) dsTongHopSuDungDichVu.BCTongHopDichVu.Clear();
                da.Fill(dsTongHopSuDungDichVu.BCTongHopDichVu);
                gridControl.DataSource = dsTongHopSuDungDichVu.BCTongHopDichVu;

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(false, gridControl, true, true, "Bảng tổng hợp sử dụng dịch vụ", "", "");
        }
    }
}
